<template>
  <!-- 普通会员等级设置 -->
  <div class="distribution-level-set1 bottom-redius">
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('user:userLevel:save')"
          class="default-btn primary-btn"
          :class="{'disabled-btn': maxNeedGrowth === 1000000000}"
          @click.stop="addRow()"
        >
          {{ $t("user.addLevel") }}
          <el-tooltip effect="light">
            <template #content>
              <div style="max-width:500px">
                {{ $t("user.addLevelTip") }}
              </div>
            </template>
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </div>
        <div
          v-if="isUpdateData && isAuth('user:userLevel:updateUserLevel')"
          class="default-btn"
          @click="updateUserLevel"
        >
          {{ $t('user.updateUserData') }}
        </div>
        <el-tag
          v-if="isUpdateData && isAuth('user:userLevel:updateUserLevel')"
          class="operation-tag"
          type="warning"
        >
          {{ $t('user.updateSoon') }}
        </el-tag>
      </div>
      <div class="table-con">
        <el-table
          :data="dataForm.userLevels"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
          class="level-table"
        >
          <el-table-column
            prop="level"
            fixed
            :label="$t('user.grade')"
            width="100"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.level }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="levelName"
            fixed
            :label="$t('user.levelName')"
            width="160"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.levelName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="levelStyle"
            fixed
            :label="$t('user.levelStyle')"
            width="160"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ [$t('user.custom'),$t('user.bronze'),$t('user.silver'),$t('user.gold')][scope.row.levelStyle] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="needGrowth"
            :label="$t('user.growthRange')"
            width="180"
          >
            <template #default="scope">
              <div>
                <span>{{ scope.row.needGrowth }}</span>
                <span v-if="scope.$index < dataForm.userLevels.length-1">~</span>
                <span
                  v-if="scope.$index < dataForm.userLevels.length-1"
                >{{ dataForm.userLevels[scope.$index+1].needGrowth-1 }}</span>
                <span v-if="scope.$index === dataForm.userLevels.length-1">~ ∞</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="userRights"
            :label="$t('user.rightsInterests')"
          >
            <template #default="scope">
              <span
                v-if="scope.row.userRights && scope.row.userRights.length !== 0"
                class="table-cell-text"
              >
                <span
                  v-for="(item, index) in scope.row.userRights"
                  :key="item.rightsId"
                >
                  {{ item.rightsName }}<span v-if="index!==scope.row.userRights.length-1">;</span>
                </span>
              </span>
              <span
                v-else
                class="table-cell-text"
              >-</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="couponNumber"
            :label="$t('user.couponNumber')"
            width="160"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.couponCount || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            align="center"
            :label="$t('crud.menu')"
            width="150"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('user:userLevel:update')"
                  class="text-btn default-btn"
                  @click="onAddOrUpdate(scope.$index)"
                >
                  {{ scope.$index+1 > maxLength ? $t('user.save') : $t('user.edit') }}
                </div>
                <div
                  v-if="scope.$index === dataForm.userLevels.length -1 && scope.$index !== 0 && isAuth('user:userLevel:delete')"
                  class="text-btn default-btn"
                  @click="deleteRow(scope.$index)"
                >
                  {{ $t('user.remove') }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshDataList"
    />
  </div>
</template>

<script setup>
import AddOrUpdate from '../../add-or-update.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils/index.js'

const dataForm = reactive({
  parentId: null,
  id: null,
  levelType: 0,
  userLevels: []
})
const userLevel = [
  {
    id: null,
    level: 0,
    levelName: '',
    levelType: 0,
    levelStyle: 0,
    needGrowth: 0,
    term: 1,
    termType: 3,
    img: '',
    discount: 10,
    discountRange: 0,
    discountType: 0,
    presScore: 0,
    rateScore: 1,
    isFreeFee: 0,
    userRightsIds: [],
    categorys: null
  }
]
onMounted(() => {
  getData()
})

const maxLength = ref(0)
const isUpdateData = ref(false)
const maxNeedGrowth = ref(0)
// 获取数据
const getData = () => {
  http({
    url: http.adornUrl('/user/userLevel/list'),
    method: 'get',
    params: http.adornParams({
      userLevelType: 0
    })
  }).then(({ data }) => {
    dataForm.userLevels = data || []
    maxLength.value = (data && data.length) || 0
    dataForm.userLevels.forEach(item => {
      if (item.status === -1) {
        isUpdateData.value = true
      }
      maxNeedGrowth.value = item.needGrowth
    })
  })
}

const handleChange = (val) => {
  dataForm.parentId = val[val.length - 1]
}

const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref(null)
// 新增 / 修改
const onAddOrUpdate = (index) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(dataForm.userLevels, index)
  })
}

// 删除列
const deleteRow = (index) => {
  ElMessageBox.confirm($t('admin.isDeleOper'), $t('text.tips'), {
    confirmButtonText: $t('user.confirm'),
    cancelButtonText: $t('user.cancel'),
    type: 'warning'
  }).then(() => {
    dataForm.id = dataForm.userLevels[index].id
    // 删除列并更新数据
    if (dataForm.id) {
      http({
        url: http.adornUrl('/user/userLevel'),
        method: 'delete',
        data: http.adornData(dataForm)
      }).then(() => {
        isUpdateData.value = false
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500
        })
        getData()
      }).catch(() => { })
    } else {
      getData()
    }
  }).catch(() => { })
}

// 增加列
const addRow = () => {
  if (maxNeedGrowth.value >= 1000000000) {
    return
  }
  if (dataForm.userLevels.length >= 50) {
    ElMessage({
      message: $t('user.atMost'),
      type: 'warning'
    })
    return
  }
  if (dataForm.userLevels.length > maxLength.value) {
    ElMessage({
      message: $t('user.saveFirst'),
      type: 'warning'
    })
    return
  }
  let needGrowth = 0
  if (dataForm.userLevels.length > 0) {
    needGrowth = dataForm.id = dataForm.userLevels[maxLength.value - 1].needGrowth === 1000000000 ? 1000000000 : dataForm.userLevels[maxLength.value - 1].needGrowth + 1
  }
  const level = JSON.parse(JSON.stringify(userLevel[0]))
  level.levelId = null
  level.level = dataForm.userLevels.length + 1
  const levelNum = parseInt(dataForm.userLevels.length) + 1
  level.levelName = $t('user.membershipLevel') + levelNum
  dataForm.userLevels.push(level)
  dataForm.userLevels[maxLength.value].needGrowth = needGrowth
  onAddOrUpdate(dataForm.userLevels.length - 1)
}

const updateUserLevel = () => {
  http({
    url: http.adornUrl('/user/userLevel/updateUserLevel'),
    method: 'put',
    data: http.adornData({
      levelType: 0
    })
  }).then(() => {
    location.reload()
  })
}

const refreshDataList = () => {
  getData()
}

defineExpose({
  handleChange
})

</script>

<style lang="scss" scoped>
.distribution-level-set1 {
  .operation-bar {
    margin-top: 5px;
    .operation-tag {
      margin-left: 20px;
    }
  }

  &:deep(.el-table__body-wrapper) {
    .el-table__fixed-right::before {
      background-color: transparent;
      height: 0;
    }
    .el-table__fixed::before {
      background-color: transparent;
      height: 0;
    }
  }
}
</style>
